package com.micro.ai.gateway.config;

import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * 网关熔断器配置
 * 基于Resilience4j实现服务熔断和降级
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Configuration
public class GatewayCircuitBreakerConfig {

    /**
     * 配置默认的熔断器规则
     */
    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                // 熔断器配置
                .circuitBreakerConfig(io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.custom()
                        // 滑动窗口大小（请求数）
                        .slidingWindowSize(20)
                        // 最小调用次数（达到此数量才开始计算失败率）
                        .minimumNumberOfCalls(10)
                        // 失败率阈值（50%失败时熔断）
                        .failureRateThreshold(50)
                        // 慢调用时间阈值
                        .slowCallDurationThreshold(Duration.ofSeconds(5))
                        // 慢调用百分比阈值
                        .slowCallRateThreshold(50)
                        // 熔断器打开后等待时间（30秒后进入半开状态）
                        .waitDurationInOpenState(Duration.ofSeconds(30))
                        // 半开状态下允许的调用数
                        .permittedNumberOfCallsInHalfOpenState(5)
                        // 自动从打开状态转换到半开状态
                        .automaticTransitionFromOpenToHalfOpenEnabled(true)
                        .build())
                // 超时配置
                .timeLimiterConfig(TimeLimiterConfig.custom()
                        .timeoutDuration(Duration.ofSeconds(10))
                        .build())
                .build());
    }

    /**
     * 为特定服务配置定制化熔断器
     */
    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> slowServiceCustomizer() {
        return factory -> factory.configure(builder -> builder
                .circuitBreakerConfig(io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.custom()
                        .slidingWindowSize(10)
                        .failureRateThreshold(60)
                        .waitDurationInOpenState(Duration.ofSeconds(60))
                        .build())
                .timeLimiterConfig(TimeLimiterConfig.custom()
                        .timeoutDuration(Duration.ofSeconds(30))
                        .build()), 
                "slowService");
    }
}
